import { ref, watch, computed } from 'vue';
import { Overlay } from 'ol';
import { Point, LineString } from 'ol/geom';
import { Style, Icon } from 'ol/style';
import { Feature } from 'ol';
import dao from '@/api/dao';
import { ElMessage } from 'element-plus';

/**
 * 轨迹数据管理与动画控制钩子
 * @param {Object} map - OpenLayers地图实例
 * @param {Object} sourceFeatures - 矢量图层数据源
 * @returns {Object} 轨迹管理相关方法和状态
 */
export function useTrajectory(map, sourceFeatures) {
  // 轨迹状态
  const path = ref([]);
  const pathPoint = ref([]);
  const pathIndex = ref(0);
  const positionList = ref([]);
  const isPlaying = ref(false);
  const userPositionData = ref(null);
  
  // 动画控制
  const setIntervalTime = ref(300);
  const splitNumber = ref(20);
  const animationId = ref(null);
  
  // 标记与样式
  const myplanImg = ref('/icons/icon-right.gif');
  const marker = ref(null);
  const helpTooltip = ref(null);
  const helpTooltipElement = ref(null);
  
  /**
   * 设置动画速度
   * @param {Number} speed - 动画间隔时间（毫秒）
   */
  function setAnimationSpeed(speed) {
    setIntervalTime.value = speed;
  }
  
  /**
   * 初始化标记叠加层
   */
  function initMarkerOverlay() {
    // 创建标记叠加层
    const markerElement = document.getElementById('geo-marker');
    marker.value = new Overlay({
      positioning: 'center-center',
      offset: [0, 0],
      element: markerElement,
      stopEvent: false
    });
    map.addOverlay(marker.value);
    
    // 创建信息提示叠加层
    helpTooltipElement.value = document.createElement('div');
    helpTooltipElement.value.className = 'measuretip';
    helpTooltipElement.value.id = 'speed';
    
    helpTooltip.value = new Overlay({
      element: helpTooltipElement.value,
      offset: [15, 0],
      positioning: 'center-left'
    });
    map.addOverlay(helpTooltip.value);
  }
  
  /**
   * 处理轨迹点数据，生成插值点
   * @param {Array} rawPath - 原始轨迹点数组
   * @param {Number} splits - 每两点间的分割数
   * @returns {Array} 处理后的轨迹点数组
   */
  function analysisPath(rawPath, splits) {
    if (!rawPath || rawPath.length < 2) return rawPath;
    
    const processedPath = [];
    
    for (let i = 0; i < rawPath.length - 1; i++) {
      const start = rawPath[i];
      const end = rawPath[i + 1];
      
      processedPath.push(start);
      
      // 生成插值点
      for (let j = 1; j < splits; j++) {
        const ratio = j / splits;
        const point = [
          start[0] + (end[0] - start[0]) * ratio,
          start[1] + (end[1] - start[1]) * ratio
        ];
        processedPath.push(point);
      }
    }
    
    // 添加最后一个点
    processedPath.push(rawPath[rawPath.length - 1]);
    return processedPath;
  }
  
  /**
   * 更新提示信息内容和位置
   * @param {Array} coordinate - 当前坐标
   * @param {String} name - 用户名称
   */
  function updateTooltipContent(coordinate, name = '用户') {
    if (!helpTooltipElement.value) return;
    
    helpTooltipElement.value.innerHTML = 
      `<B>名称：</B>${name}` +
      '<br>' +
      '<B>经纬度：</B>' +
      (coordinate[0] + '').substring(0, 8) +
      ',' +
      (coordinate[1] + '').substring(0, 8);
    
    helpTooltip.value.setPosition(coordinate);
  }
  
  /**
   * 使用requestAnimationFrame实现轨迹动画
   * @param {Boolean} loop - 是否循环播放
   * @returns {Function} 停止动画的函数
   */
  function startAnimation(loop = false) {
    if (pathPoint.value.length === 0 || isPlaying.value) return;
    
    isPlaying.value = true;
    let lastFrameTime = 0;
    
    const animate = (timestamp) => {
      if (!isPlaying.value) return;
      
      const elapsed = timestamp - lastFrameTime;
      
      if (elapsed >= setIntervalTime.value) {
        if (pathIndex.value >= 0 && pathIndex.value < pathPoint.value.length) {
          // 获取当前点和前一个点
          const currentPoint = pathPoint.value[pathIndex.value];
          const prevPoint = pathIndex.value > 0 ? pathPoint.value[pathIndex.value - 1] : currentPoint;
          
          // 设置标记位置
          marker.value.setPosition(currentPoint);
          
          // 根据X轴变化方向调整图标
          if (currentPoint[0] > prevPoint[0]) {
            myplanImg.value = '/icons/icon-right.gif';
          } else if (currentPoint[0] < prevPoint[0]) {
            myplanImg.value = '/icons/icon-left.gif';
          }
          
          // 更新提示内容
          updateTooltipContent(currentPoint);
          
          // 更新路径索引
          pathIndex.value++;
        } else {
          // 动画结束，如果需要循环则重置索引
          if (loop) {
            pathIndex.value = 0;
          } else {
            isPlaying.value = false;
            return;
          }
        }
        
        lastFrameTime = timestamp;
      }
      
      // 请求下一帧
      animationId.value = requestAnimationFrame(animate);
    };
    
    // 启动动画
    animationId.value = requestAnimationFrame(animate);
    
    // 返回停止函数
    return stopAnimation;
  }
  
  /**
   * 停止轨迹动画
   */
  function stopAnimation() {
    isPlaying.value = false;
    if (animationId.value) {
      cancelAnimationFrame(animationId.value);
      animationId.value = null;
    }
  }
  
  /**
   * 重置轨迹动画到起点
   */
  function resetAnimation() {
    stopAnimation();
    pathIndex.value = 0;
  }
  
  /**
   * 显示轨迹起点和终点标记
   */
  function showStartEndMarkers() {
    if (path.value.length < 2) return;
    
    // 创建起点和终点样式
    const markerStyle = new Style({
      image: new Icon({
        src: '/icons/destination.png',
        scale: 0.03,
        anchor: [0.5, 0.5]
      })
    });
    
    // 创建起点和终点要素
    const startFeature = new Feature({
      geometry: new Point(path.value[0])
    });
    
    const endFeature = new Feature({
      geometry: new Point(path.value[path.value.length - 1])
    });
    
    // 设置样式并添加到图层
    startFeature.setStyle(markerStyle);
    endFeature.setStyle(markerStyle);
    sourceFeatures.addFeatures([startFeature, endFeature]);
  }
  
  /**
   * 绘制轨迹线
   * @param {Object} lineString - LineString几何对象
   */
  function drawTrajectoryLine(lineString) {
    if (path.value.length < 2) return;
    lineString.setCoordinates(path.value);
  }
  
  /**
   * 加载并处理用户轨迹数据
   * @param {Object} userVO - 用户和查询参数
   * @param {Object} lineString - LineString几何对象
   * @returns {Promise} 加载结果Promise
   */
  async function loadUserTrajectory(userVO, lineString) {
    try {
      // 重置数据
      userPositionData.value = null;
      path.value = [];
      pathPoint.value = [];
      pathIndex.value = 0;
      
      // 请求用户位置数据
      const response = await dao.getUserPosition(userVO);
      const data = response.data.data;
      
      // 验证数据有效性
      if (!data || !data.positions || data.positions.length < 2) {
        throw new Error('位置数据不足，请更换查询条件');
      }
      
      // 设置数据
      userPositionData.value = data;
      positionList.value = data.positions;
      
      // 构建路径坐标数组
      path.value = positionList.value.map(p => [p.lon, p.lat]);
      
      // 处理轨迹点，生成插值
      pathPoint.value = analysisPath(path.value, splitNumber.value);
      
      // 绘制轨迹线
      drawTrajectoryLine(lineString);
      
      // 显示起点和终点标记
      showStartEndMarkers();
      
      // 初始化叠加层
      initMarkerOverlay();
      
      return { success: true, data };
    } catch (error) {
      console.error('加载用户轨迹失败:', error);
      ElMessage.error(error.message || '加载用户轨迹失败');
      return { success: false, error };
    }
  }
  
  return {
    // 状态
    path,
    pathPoint,
    pathIndex,
    positionList,
    userPositionData,
    isPlaying,
    myplanImg,
    
    // 配置
    setIntervalTime,
    splitNumber,
    
    // 方法
    analysisPath,
    loadUserTrajectory,
    startAnimation,
    stopAnimation,
    resetAnimation,
    setAnimationSpeed,
    updateTooltipContent,
    showStartEndMarkers,
    drawTrajectoryLine
  };
} 